'''
Created on 16 Apr 2012

@author: karulis
'''

from PySide import QtGui
from BaseTab import BaseTab

class GroupsAddTab(BaseTab):
    '''
    classdocs
    '''


    def __init__(self, parent = None):
        '''
        Constructor
        '''
        super(GroupsAddTab, self).__init__(parent)

        userLabel = QtGui.QLabel("User:")
        self.combo = QtGui.QComboBox()

        groupsLabel = QtGui.QLabel("All groups:")
        self.groupsListBox = QtGui.QListWidget()

        removeButton = QtGui.QPushButton("Add to group")
        removeButton.clicked.connect(self.add_clicked)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(userLabel)
        mainLayout.addWidget(self.combo)
        mainLayout.addWidget(groupsLabel)
        mainLayout.addWidget(self.groupsListBox)
        mainLayout.addWidget(removeButton)

        mainLayout.addStretch(1)
        self.setLayout(mainLayout)
        self.refresh_gui()

    def refresh_gui(self):
        self.combo.clear()
        users = self.get_users()
        self.combo.addItems(users.keys())

        groups = self.get_all_groups()
        self.groupsListBox.insertItems(0, groups)

    def get_all_groups(self):
        return self.execute("cat /etc/group |cut -d: -f1").split()

    def add_clicked(self):
        row = self.groupsListBox.currentRow()
        if row >= 0:
            group = self.groupsListBox.item(row).text()
            user = self.combo.currentText()
            ret = self.execute("usermod -aG " + group + " " + user)
            if "" != ret:
                self.show_message(ret)
            else:
                self.refresh.emit()
